import HTTP from './http';
import { GLOBAL } from '../config/global';
import StorageHelper from './storageHelper';
import { STORAGE_CONSTANT } from '../config/storage';
import ToastUtil from './toast';
import { API, API_GENERATE } from '../config/api';

class Permission {

	permissions = [];

	init () {
		return new Promise(async (resolve) => {
			if (!GLOBAL.TOKEN) return resolve([]);
			try {
				this.permissions = await HTTP.GET(API_GENERATE(API.GET_PERMISSION_LIST));
				await StorageHelper.set(STORAGE_CONSTANT.PERMISSIONS, this.permissions);
			} catch (err) {
				this.permissions = [];
				ToastUtil.showError('获取权限异常，请重试');
				await StorageHelper.set(STORAGE_CONSTANT.PERMISSIONS, this.permissions);
			} finally {
				resolve(this.permissions)
			}
		})
	}

	check (code) {
		if (!this.permissions) this.init();
		return !code || (code && this.permissions && this.permissions.indexOf(code) != -1)
	}
}

module.exports = new Permission();